<?php

namespace app\common\logic;

use app\common\enum\YesNoEnum;
use app\common\model\callback\OrderCallback;
use app\common\model\return_rule\ReturnRule;
use app\common\model\return_rule\ReturnRuleDetail;
use think\facade\Cache;


/**
 * 订单回调逻辑层
 * Class NoticeLogic
 * @package app\common\logic
 */
class OrderCallbackLogic extends BaseLogic
{

    private static $prefix = 'order_callback_';

    /**
     * @notes 判断订单是否需要回传
     * @param $params
     * @return bool
     * @author 段誉
     * @date 2022/9/15 15:28
     */
    public static function payIsHc($promotion_link_id,$user_callback,$order)
    {
        $is_hc = true;
        $time = time();
        $date_pattern = 0;
        //查询推广链绑定回传规则
        $returnRule = ReturnRule::where('promotion_link_id',$promotion_link_id)->findOrEmpty();
        if (!$returnRule->isEmpty()){
            //1.先判断推广链是否为开启状态，如果没开启不回传
            if ($returnRule->status==0){
                $is_hc = false;
                $message = '推广链未开启';
                dump($message);
                //推广链未生效执行回传 return
                return $is_hc;
            }
            //2.先判断推广链是否到达生效时间，如果没生效不回传
            if (strtotime($returnRule->time)>$time){
                $is_hc = false;
                $message = '推广链未到生效时间';
                dump($message);
                //推广链未生效执行回传 return
                return $is_hc;
            }
            //3.判断附加规则里面是否配置了全量回传的订单
            if($returnRule->additional_num>0){
                //如果配置了全量回传，查询推广链已回传的订单数，如果小于全量订单直接回传
                if (OrderCallback::where(['promotion_link_id'=>$promotion_link_id,'return_status'=>1])->count()<$returnRule->additional_num){
                    $is_hc = true;
                    $message = '触发附加全量回传规则';
                    dump($message);
                    //到达全量附加规则执行回传 return
                    return $is_hc;
                }
            }

            //4:判断是否满足日期模式
            switch ($returnRule->date_pattern){
                case 1:
                    //先获取天数时间戳，如果小时大于0再加上小时的时间戳，从当天开始算   1:天数 2：24小时 3：小时
                    $date_pattern = strtotime('+1 day', strtotime(date('Y-m-d', $user_callback->dyeing_time))) - $user_callback->dyeing_time+($returnRule->day-1)*86400;
                    if ($returnRule->hour>0){
                        $date_pattern += $returnRule->hour*3600;
                    }
                    break;
                case 2:
                    $date_pattern = 86400;
                    break;
                case 3:
                    $date_pattern = $returnRule->hour*3600;
                    break;
            }

            if ($date_pattern<$time-$user_callback->dyeing_time){
                //超过染色日期不回传
                $message = '超过染色日期不回传';
                dump($message);
                $is_hc = false;

            }else{
                //5:判断上传口径 如果上传口径只回传首单，判断用户回传订单是否已回传此推广链
                if ($returnRule->type==1){
                    if (OrderCallback::where(['promotion_link_id'=>$promotion_link_id,'return_status'=>1,'user_id'=>$user_callback->user_id])->count()>0){
                        //已满足上报口径，不回传
                        $message = '已满足上报口径不回传';
                        dump($message);
                        $is_hc = false;
                    }
                }
            }

            //如果走到这等于true，说明满足前面所有回传条件，走订单范围判断
            if ($is_hc){
                //6：判断订单范围 先判断订单金额满足哪个区间，然后判断回传详情的状态
                $where = [];
                $where[] = ['return_rule_id','=',$returnRule->id];
                $where[] = ['min_price','<=',$order->money];
                $where[] = ['max_price','>=',$order->money];
                $returnRuleDetail = ReturnRuleDetail::where($where)->findOrEmpty();
                if (!$returnRuleDetail->isEmpty()){
                    //判断回传类型
                    switch ($returnRuleDetail->return_type){
                        case 1:
                            //全部回传
                            $is_hc = true;
                            $message = '订单金额配置全部回传-执行回传';
                            dump($message);
                            //到达全量附加规则执行回传 return
                            return $is_hc;
                            break;
                        case 2:
                            //全部扣除
                            $is_hc = false;
                            $message = '订单金额配置全部扣除-不回传';
                            dump($message);
                            //到达全量附加规则执行回传 return
                            break;
                        case 3:
                            //自定义  1：获取当前已经回传数，如果回传数>=配置回传数则增加漏传数否则执行回传并增加回传数 2：如果漏传数>=配置的漏传数则回传该笔订单，将回传数设置为1并将回传数设置为0
                            //自定义  1：获取当前已经回传数，如果回传数小于配置回传数，缓存回传数+1，并直接回传 2：如果
                            $reported_num = self::getCacheReportedNum($promotion_link_id);
                            $missed_num = self::getCacheMissedNum($promotion_link_id);
                            //小于回传数，执行回传，缓存回传数+1
                            if ($reported_num<$returnRuleDetail->reported_num){
                                $is_hc = true;
                                $message = '命中订单自定义规则-执行回传';
                                dump($message);
                                self::incReportedNum($promotion_link_id,$reported_num,$missed_num);
                                //到达全量附加规则执行回传 return
                                return $is_hc;
                            }
                            //缓存扣除数大于扣配置除传数，充值推广链回传规则详情缓存
                            if ($missed_num>=$returnRuleDetail->missed_num){
                                $is_hc = true;
                                $message = '命中订单自定义规则-执行回传';
                                dump($message);
                                self::resetReturnRuleDetail($promotion_link_id);
                                return $is_hc;
                            }else{
                                $is_hc = false;
                                $message = '命中订单自定义规则执行扣除-不回传';
                                dump($message);
                                self::incMissedNum($promotion_link_id,$reported_num,$missed_num);
                            }
                            break;
                    }

                }else{
                    //未匹配到订单回传规则，不回传
                    $is_hc = false;
                    $message = '未匹配到订单回传规则不回传';
                    dump($message);
                }
            }

            //判断附加小时
            if($returnRule->additional_hour>0&&$order->money>$returnRule->additional_price){
                //获取时间
                $diff_time = $time -$user_callback->dyeing_time ;
                if ($returnRule->additional_hour*3600>=$diff_time){
                    //满足附加时间规则
                    $is_hc = true;
                    $message = $message.'--满足附加时间规则-执行回传';
                    dump($message);
                    return $is_hc;
                }
            }
            //未满足所以条件，走到这$is_hc就是false
        }
        return $is_hc;
    }
    /*
     * 将数据缓存到database2里面
     * */
    public static function redisCache()
    {
        $cache = Cache::store('redis');
        $cache->handler()->select(2);
        return $cache;
    }
    //获取推广链缓存的上报数
    public static function getCacheReportedNum($promotion_link_id)
    {
        $key = self::$prefix.$promotion_link_id;
        return self::redisCache()->get($key)['report_num'] ?? 0;
    }
    //获取推广链缓存的扣除数
    public static function getCacheMissedNum($promotion_link_id)
    {
        $key = self::$prefix.$promotion_link_id;
        return self::redisCache()->get($key)['missed_num'] ?? 0;
    }
    //缓存推广链上报数+1
    public static function incReportedNum($promotion_link_id,$report_num,$missed_num)
    {
        $difftime = strtotime('tomorrow')-time();
        $key = self::$prefix.$promotion_link_id;
        self::redisCache()->set($key, ['report_num' => $report_num+1,'missed_num' => $missed_num], $difftime);
        return true;
    }
    //缓存推广链扣除数+1
    public static function incMissedNum($promotion_link_id,$report_num,$missed_num)
    {
        $difftime = strtotime('tomorrow')-time();
        $key = self::$prefix.$promotion_link_id;
        self::redisCache()->set($key, ['report_num' => $report_num,'missed_num' => $missed_num+1], $difftime);
        return true;
    }
    //充值推广链 上报数设置为1 扣除数设置为0
    public static function resetReturnRuleDetail($promotion_link_id)
    {
        $difftime = strtotime('tomorrow')-time();
        $key = self::$prefix.$promotion_link_id;
        self::redisCache()->set($key, ['report_num' => 1,'missed_num' => 0], $difftime);
        return true;
    }

    public static function reportingBehavior($return_rule_id,$user_id){

    }


}